package cn.wawi.controller.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.wawi.common.ResultData;
import com.wawi.common.annotation.Permission;
import cn.wawi.controller.BaseController;
import cn.wawi.dao.sys.PrivilegeDao;
import cn.wawi.dao.sys.RoleDao;
import cn.wawi.entity.sys.Privilege;
import cn.wawi.entity.sys.Role;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/sys_role")
public class RoleController extends BaseController<Role>{
	
	@Resource
	protected RoleDao<Role> roleDao;
	@Resource
	protected PrivilegeDao<Privilege> privilegeDao;
	/**
	 *主页
	 */
	@RequestMapping(value="/main",method=RequestMethod.GET)
	public String main() {
		return "sys/Role/main";
	}
	/*
	 * 获取用户角色
	 */
	@ResponseBody
	@RequestMapping(value="/getUserRole",method=RequestMethod.GET)
	public List<Role> getUserRole(String userId){
		return roleDao.getUserRole(userId);
	}
	/*
	 * 保存用户角色
	 */
	@Permission("sys:user:saveUserRole")
	@ResponseBody
	@RequestMapping(value="/saveUserRole",method=RequestMethod.POST)
	public ResultData<Role> saveUserRole(String userId,String roleId){
		roleDao.deleteUserRole(userId);
		if(roleId!=null&&!"".equals(roleId.trim())){
			for (String s: roleId.split(",")) {
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("userId",userId);
				map.put("roleId", s);
				roleDao.saveUserRole(map);
			}
		}
		return new ResultData<Role>();
	}
	/*
	 * 获取角色权限
	 */
	@ResponseBody
	@RequestMapping(value="/getRolePrivilege",method=RequestMethod.GET)
	public List<Privilege> getRolePrivilege(String id){
		List<Privilege> list=privilegeDao.findRolePrivilege(id);
		return list;
	}
	/*
	 * 保存角色权限
	 */
	@Permission("sys:role:saveRolePrivilege")
	@ResponseBody
	@RequestMapping(value="/saveRolePrivilege",method=RequestMethod.POST)
	public ResultData<Role> saveRolePrivilege(String roleId,String privilegeIds){
		roleDao.deleteRolePrivilege(roleId);
		if(privilegeIds!=null&&!"".equals(privilegeIds.trim())){
			String[] privileges=privilegeIds.split(",");
			for (String p: privileges) {
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("roleId", roleId);
				map.put("privilegeId", p);
				roleDao.saveRolePrivilege(map);
			}
		}
		return new ResultData<Role>();
	}
}
